const path = require('path')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { DefinePlugin } = require('webpack')
const CopyWebpakcPlugin = require('copy-webpack-plugin')

module.exports = {
  entry: "./src/main.js",
  output: {
    filename: 'js/bundle.js',
    // 必须是一个绝对路径
    path: path.resolve(__dirname, './build')
    // assetModuleFilename: 'img/[name][hash:6][ext]'
  },
  module: {
    // rule对象
    rules: [
      {
        // 匹配资源 正则表达式
        test: /\.css$/,
        // loader: 'css-loader' use 简写
        use: [
          // 编译顺序：从后往前，从下往上
          // useEntry 对象
          // { loader: 'css-loader' }
          // 'css-loader' { loader: 'css-loader' } 简写5
          "style-loader",
          {
            loader: "css-loader",
            options: {
              importLoaders: 1
            }
          },
          "postcss-loader"
        ]
      },
      {
        test: /\.less$/,
        use: [
          'style-loader',
          {
            loader: "css-loader",
            options: {
              importLoaders: 2
            }
          },
          "postcss-loader",
          'less-loader'
        ]
      },
      {
        test: /\.(png|jpe?g|gif|svg)$/,
        // type: 'asset/resource', // 打包文件 file-loader
        // type: 'asset/inline',  // 打包url url-loader
        type: 'asset',
        generator: {
          filename: 'img/[name][hash:6][ext]'
        },
        parser: {
          dataUrlCondition: {
            maxSize: 2 * 1021 * 1024
          }
        }
      },
      {
        test: /\.ttf|eot|woff2?$/i,
        type: 'asset/resource',
        generator: {
          filename: 'font/[name].[hash:6][ext]'
        }
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      title: '05_webpack最实用plugin',
      template: './public/index.html'
    }),
    new DefinePlugin({
      BASE_URL: '"./"'
    }),
    new CopyWebpakcPlugin({
      patterns: [
        {
          from: 'public',
          globOptions: {
            ignore: [
              '**/index.html',
              '**/abc.txt'
            ]
          }
        }
      ]
    })
  ]
}